#!/usr/bin/python

import fontforge
import sys
import os
import tempfile

def makename (name):
	if font[name].unicode > 0:
		return '"' + unichr (font[name].unicode).encode ('utf-8').replace ('\\', '\\\\').replace ('"', r'\"') + '"'
	else:
		return '"_%s"' % name

def add_glyph (name, glyph):
	if all ([glyph.layers[x].isEmpty () for x in glyph.layers]):
		if len (glyph.references) == 0:
			if glyph.unicode == 32:
				glyphs[glyph.unicode] = (glyph.width, glyph.vwidth, '', ())
			return
		dxf = ''
	else:
		refs = glyph.references
		glyph.references = ()
		dxfbase = glyphname + os.extsep + 'dxf'
		dxf = os.path.join (sys.argv[2], dxfbase)
		if not os.path.exists (dxf):
			glyph.export (eps)
			os.system ('pstoedit -dt -f dxf:-polyaslines %s %s' % (eps, dxf))
		glyph.references = refs
	glyphs[glyphname] = (glyph.width, glyph.vwidth, dxf, glyph.references)
	for r in glyph.references:
		if r[0] not in glyphs:
			add_glyph (r[0], font[r[0]])

if not os.path.exists (sys.argv[2]):
	os.makedirs (sys.argv[2])
eps = tempfile.mkstemp (prefix = 'mkfont-', suffix = os.extsep + 'eps')[1]
try:
	font = fontforge.open (sys.argv[1])
	glyphs = {}
	for glyphname in font:
		if glyphname in glyphs:
			# This glyph was inserted because it was included by another glyph.
			continue
		glyph = font[glyphname]
		# Select which glyphs to convert.  TODO.
		add_glyph (glyphname, glyph)
finally:
	os.unlink (eps)

with open (os.path.join (sys.argv[2], 'font' + os.extsep + 'scad'), 'w') as f:
	f.write ('font_%s = [[%f, %f], [\n' % (sys.argv[2], font.ascent / 72., font.descent / 72.))
	f.write ('\t["",\t0,\t0,\t""],\n\n')	# Invalid character.
	names = glyphs.keys ()
	names.sort (key = lambda x: makename (x))
	for g in names:
		f.write ('\t[%s,\t%f,\t%f,\t"%s", [%s]],\n' % (makename (g), glyphs[g][0] / 72., glyphs[g][1] / 72., glyphs[g][2], ', '.join (['[%s, [[%f, %f, 0, %f], [%f, %f, 0, %f], [0, 0, 1, 0], [0, 0, 0, 1]]]' % (makename (x[0]), x[1][0], x[1][2], x[1][4] / 72., x[1][1], x[1][3], x[1][5] / 72.) for x in glyphs[g][3]])))
	f.write (']];\nfont_default = font_%s;\n' % sys.argv[2])
